import { useAdminStore } from '@/stores/admin-store';
import { useGlobalStore } from '@common/store/global-store';
import { usePrivateMicroStore } from '@common/store/micro-store';
import { getAjaxInstance, useJE } from '@jecloud/utils';
import MicroApp, { loadMicroApp } from '@/assets/micro-app';
import publicConfig from '@build/public/src/config.json';
import { CLI_ENVS } from '@common/helper/constant';
import { MicroActiveType } from '@/data/enum/micro';
import { useRouter } from '@common/router';
// 生产环境
const production = CLI_ENVS.NODE_ENV === 'production';
// 动态加载的app
const dynamicApps = {};

/**
 * 动态加载app
 * @param {*} name
 * @returns
 */
export function loadDynamicApp(name) {
  const adminStore = useAdminStore();
  if (dynamicApps[name]) {
    return Promise.resolve({ mounted: true });
  } else if (!adminStore.hasMicroConfig(name)) {
    return Promise.reject(404);
  } else {
    dynamicApps[name] = true;
    const container = document.createElement('div');
    container.setAttribute('id', 'micro-app-plugin-' + name);
    container.style.width = 0;
    container.style.height = 0;
    document.body.appendChild(container);
    return setupMicro({ name, container, layout: MicroActiveType.PLUGIN }).then(() => {
      return { mounted: false };
    });
  }
}
/**
 * 打开微应用窗口
 * @param {*} name
 * @param {*} options
 */
export function openMicroApp(name, options = {}) {
  const router = useRouter();
  const globalStore = useGlobalStore();
  const { query, layout = 'app', plan = globalStore.activePlan } = options;
  const { href } = router.resolve({ params: { plan, layout, menu: name }, query });
  window.open(href);
}

/**
 * 安装微应用
 */
export function setupMicro(options) {
  const { name, container, props = {}, querys = {} } = options;
  const adminStore = useAdminStore();
  if (!adminStore.hasMicroConfig(name)) {
    return Promise.reject(404);
  }
  const app = adminStore.getMicroConfig(name);
  // 微应用参数
  const router = useRouter();
  const appName = adminStore.getMicroName(options);
  // 先销毁历史app
  adminStore.destroyMicro(options);
  // 微应用store
  const store = usePrivateMicroStore(appName);
  // 参数
  Object.assign(store.props, props);
  // 配置项
  Object.assign(store.options, app);
  // 主应用事件触发函数
  store.emitAdmin = (...args) => {
    adminStore.emit(...args);
  };
  // 触发其他微应用事件
  store.emitMicro = (...args) => {
    adminStore.emitMicro(...args);
  };
  // 绑定主应用信息
  store.setupAdmin = ({ MicroJE }) => {
    // 注册微应用JE可以调用主应用的信息
    MicroJE.useAdmin = useJE().useAdmin;
  };
  // 微应用传参
  const microProps = {
    microStore: store,
    globalStore: useGlobalStore(),
    ajaxInstance: getAjaxInstance(),
    querys: { ...querys, ...router.currentRoute.value.query },
  };
  // 解析激活路由参数
  store.options.activeRoute = app.parseActiveRoute(microProps.querys);
  // 实例
  store.instance = loadMicroApp({
    name: appName,
    url: app.getEntryUrl(),
    container,
    props: microProps,
  });
  // 注册微应用
  adminStore.setupMicro({ ...options, store });
  return store.instance.mountPromise;
}

/**
 * 卸载微应用
 * @param {*} name
 */
export function destroyMicro(options) {
  const adminStore = useAdminStore();
  adminStore.destroyMicro(options);
}

/**
 * 初始化微应用
 */
export function startMicroApp() {
  const libs = [];
  if (production) {
    // 公共资源，子应用共享
    publicConfig.libs.forEach((lib) => {
      libs.push(`${CLI_ENVS.PUBLIC_PATH ?? '/'}static/libs/${lib.lib}/${lib.version}/min.js`);
    });
  }

  // 初始化微应用
  MicroApp.start({
    globalAssets: { js: libs },
    globalScripts({ url, globalScripts }) {
      // 公共资源
      const keys = Array.from(globalScripts.keys()) ?? [];
      return globalScripts.get(keys.find((key) => url.endsWith(key)));
    },
  });
}
/**
 * 初始化微应用数据
 * @returns
 */
export function initMicroConfig() {
  const adminStore = useAdminStore();
  return adminStore.initMicroConfig();
}
